import React from 'react'
import { connect } from 'react-redux'
import { messages } from "share/common"
import { Form, Card, Input, Radio, Select, Button, message, Icon, InputNumber, Popover } from 'antd'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
import LanguageInput from 'components/template/language-input/language-input'
import workflowService from 'containers/setting/workflow/workflow.service'
import workflowUtil from 'containers/setting/new-workflow/utils'

class NodeApproveMan extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      ruleApprovalNodeOID: '',
      selectApprovalRule: 5005,
      showDepManager: false, //【包含申请人】是否选择部门经理
      formFieldList: null, //表单条件字段 字段类型(100默认, 101文本, 102整数, 103日期, 104浮点数, 105日期, 106值列表, 107GPS, 108布尔)
      formFieldCostCenterList: null, //审批条件为成本中心属性字段
      isRuleInEdit: false, //是否有审批条件处于编辑状态
      approvalOvertimeDay:'0-0',//审批超时时间 例0天0时
      nodeNameObj: {
        i18n: null,
        remark: null
      },
    }
  }

  componentDidMount() {
    this.setState({
      ruleApprovalNodeOID: this.props.basicInfo.ruleApprovalNodeOID,
      selectApprovalRule: this.props.basicInfo.selfApprovalRule,
      approvalOvertimeDay:this.props.basicInfo.approvalOvertimeDay,
      showDepManager: !(this.props.basicInfo.selfApprovalRule === 5001 || this.props.basicInfo.selfApprovalRule === 5002 || this.props.basicInfo.selfApprovalRule === 5006)
    })
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.ruleApprovalNodeOID !== nextProps.basicInfo.ruleApprovalNodeOID) {
      let selfApprovalRuleFlag = (nextProps.basicInfo.selfApprovalRule === 5001 || nextProps.basicInfo.selfApprovalRule === 5002 ||  nextProps.basicInfo.selfApprovalRule === 5006);
      this.setState({
        ruleApprovalNodeOID: nextProps.basicInfo.ruleApprovalNodeOID,
        selectApprovalRule: selfApprovalRuleFlag ? 5005 :nextProps.basicInfo.selfApprovalRule,
        showDepManager: !selfApprovalRuleFlag,
      },() => {
        this.props.form.resetFields()
      })
      this.setState({
        approvalOvertimeDay:nextProps.basicInfo.approvalOvertimeDay
      })
    }
  }

  //保存基础信息
  handleSaveBasicInfo = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { basicInfo } = this.props;
        if (values.selfApprovalRule === 50035005) {
          values.selfApprovalRule = this.state.selectApprovalRule
        }
        let params = values;
        params.approvalActions = basicInfo.approvalActions;
        params.code = basicInfo.code;
        params.name = basicInfo.name;
        params.notifyInfo = basicInfo.notifyInfo;
        params.repeatRule = basicInfo.repeatRule;
        params.ruleApprovalNodeOID = basicInfo.ruleApprovalNodeOID;
        params.status = basicInfo.status;
        params.type = basicInfo.type;
        if (this.state.nodeNameObj.i18n) {
          params.i18n = {};
          params.i18n['remark'] = this.state.nodeNameObj.i18n;
        }else{
          params.i18n = basicInfo.i18n;
        }
        params.approvalOvertimeDay = this.state.approvalOvertimeDay;
        this.setState({ loading: true });
        workflowService.modifyApprovalNodes(params).then(() => {
          this.setState({ loading: false });
          this.props.basicInfoSaveHandle();
          message.success(messages('common.save.success', {name: ''}))
        }).catch(() => {
          this.setState({ loading: false })
        })
      }
    })
  };

  onChangeDay = (res) => {
    if (res > 999) {
      res = 999;
    }
    if (res === '') {
      res = 0;
    }
    let {approvalOvertimeDay} = this.state;
    let approvalOver = (approvalOvertimeDay && approvalOvertimeDay.split('-')) || [0, 0];
    this.setState({
      approvalOvertimeDay: res + '-' + approvalOver[1]
    })
  };

  onChangeTime = (res) => {
    if (res > 23) {
      res = 23;
    }
    if (res === '') {
      res = 0;
    }
    let {approvalOvertimeDay} = this.state;
    let approvalOver = (approvalOvertimeDay && approvalOvertimeDay.split('-')) || [0, 0];
    this.setState({
      approvalOvertimeDay: approvalOver[0] + '-' + res
    })
  };

  handleRemarkChange = (value,i18n) => {
    let { nodeNameObj } = this.state;
    nodeNameObj.remark = value;
    nodeNameObj.i18n = i18n;
    this.setState({ nodeNameObj });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { basicInfo, formInfo, language } = this.props;
    const { loading, selectApprovalRule, showDepManager, approvalOvertimeDay, nodeNameObj } = this.state;
    let selfApprovalRule = basicInfo.selfApprovalRule;
    selfApprovalRule = (selfApprovalRule === 5001 || selfApprovalRule === 5002 || selfApprovalRule === 5006) ? selfApprovalRule : 50035005;
    const formItemLayout = {
      labelCol: {span: language.code === 'zh_cn' ? 4 : 6},
      wrapperCol: {span: language.code === 'zh_cn' ? 20 : 18},
    };
    return (
      <div className='node-approve-man'>
        <Card className="basic-info-container">
          <h3 className="title">{messages('setting.key1371'/*基础信息*/)}</h3>
          <Form onSubmit={this.handleSaveBasicInfo}>
            <FormItem {...formItemLayout} label={messages('setting.key1372'/*节点名称*/)} colon={false}>
              {getFieldDecorator('remark', {
                initialValue: basicInfo.remark
              })(
                <LanguageInput
                  name={nodeNameObj.remark || basicInfo.remark }
                  width={300}
                  inpRule={workflowUtil.getInpRule(100, this.props.languageList)}
                  i18nName={nodeNameObj.i18n || (basicInfo.i18n && nodeNameObj.i18n)}
                  isEdit
                  nameChange={this.handleRemarkChange}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key1382'/*节点为空时*/)} colon={false}>
              {getFieldDecorator('nullableRule', {
                initialValue: basicInfo.nullableRule
              })(
                <RadioGroup>
                  <Radio value={2001}>{messages('setting.key1383'/*跳过*/)}</Radio>
                  <Radio value={2002}>{messages('setting.key1384'/*不跳过*/)}</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key1385'/*会签规则*/)} colon={false}>
              {getFieldDecorator('countersignRule', {
                initialValue: basicInfo.countersignRule
              })(
                <RadioGroup>
                  <Radio value={3001}>{messages('setting.key1386'/*所有人审批通过*/)}</Radio>
                  <Radio value={3002}>{messages('setting.key1387'/*任意人审批通过*/)}</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key1388'/*包含申请人*/)} colon={false}>
              {getFieldDecorator('selfApprovalRule', {
                initialValue: selfApprovalRule
              })(
                <RadioGroup onChange={e => this.setState({
                  showDepManager: e.target.value === 50035005,
                  selectApprovalRule: e.target.value === 50035005 ? 5005 : e.target.value
                })}>
                  <Radio value={5002}>{messages('setting.key1384'/*不跳过*/)}</Radio>
                  <Radio value={5001}>{messages('setting.key1383'/*跳过*/)}</Radio>
                  {/* 5005 本级、5003上级 */}
                  <Radio value={50035005}>
                    {messages('setting.key1389'/*转交部门经理*/)}
                    {showDepManager && (
                      <Select className="approval-select" value={selectApprovalRule}
                              onChange={value => {this.setState({selectApprovalRule: value})}}>
                        <Option value={5005}>{messages('setting.key1390'/*本级*/)}</Option>
                        <Option value={5003}>{messages('setting.key1391'/*上级*/)}</Option>
                      </Select>
                    )}
                  </Radio>
                  <Radio value={5006}>{messages('setting.key2056')/*转交直属领导*/}</Radio>
                </RadioGroup>
              )}
            </FormItem>
            {/*报销单的formType以3开头，只有报销单才可以选择是否允许修改费用*/}
            {formInfo.formType && String(formInfo.formType).charAt(0) === '3' && (
              <FormItem {...formItemLayout} label={messages('setting.key1392'/*允许修改费用*/)} colon={false}>
                {getFieldDecorator('invoiceAllowUpdateType', {
                  initialValue: basicInfo.invoiceAllowUpdateType || 0
                })(
                  <RadioGroup>
                    <Radio value={1}>{messages('setting.key1393'/*是*/)}</Radio>
                    <Radio value={0}>{messages('setting.key1394'/*否*/)}</Radio>
                  </RadioGroup>
                )}
              </FormItem>
            )}
            <FormItem {...formItemLayout} label={messages('setting.key1634')/*审批超时*/} colon={false}>
              <Popover overlayStyle={{maxWidth: 300}}
                       content={messages('setting.key1635')/*审批人收到审批任务，超过当前时长定义未处理视为超时，可配合单据提醒功能向审批人发送消息提醒；当超时定义为0时，当前审批环节永不超时。*/}
                       trigger="hover">
                <Icon type="info-circle" className='default-color-font' style={{marginRight: '10px'}}/>
              </Popover>
              <InputNumber min={0}
                           max={999}
                           value={approvalOvertimeDay ? Number(approvalOvertimeDay.split('-')[0]) : 0}
                           onChange={this.onChangeDay}/>{messages('setting.key753')/*天*/}
              <InputNumber style={{marginLeft: 10}}
                           min={0}
                           max={23}
                           value={approvalOvertimeDay ? Number(approvalOvertimeDay.split('-')[1]) : 0}
                           onChange={this.onChangeTime}/>{messages('setting.key1654')/*小时*/}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key1799')/*允许修改单据*/} colon={false}>
              {getFieldDecorator('editable', {
                initialValue: basicInfo.editable || false
              })(
                <RadioGroup>
                  <Radio value={true}>{messages('setting.key1393'/*是*/)}</Radio>
                  <Radio value={false}>{messages('setting.key1394'/*否*/)}</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')}</Button>
          </Form>
        </Card>
        <div className="add-btn-container">
          <Button type="primary" onClick={() => this.props.modalVisibleHandle(true)}>{messages('setting.key1395'/*添加审批人员*/)}</Button>
          <Icon type="exclamation-circle-o" className="approve-info-icon"/>
          <span className="approve-info-text">{messages('setting.key1381'/*一个条件组内多条件为and关系, 不同条件组为or关系*/)}</span>
        </div>
      </div>
    )
  }
}

NodeApproveMan.propTypes = {
  basicInfo: React.PropTypes.object,
  formInfo: React.PropTypes.object,
  basicInfoSaveHandle: React.PropTypes.func, //基本信息保存成功的回调
  modalVisibleHandle: React.PropTypes.func, //用于添加审批人modal是否显示的传参
};

NodeApproveMan.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    languageList: state.login.languageList,
    language: state.main.language
  }
}

const wrappedNodeApproveMan = Form.create()(NodeApproveMan);

export default connect(mapStateToProps)(wrappedNodeApproveMan)
